﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SBLib.Common.JsonKS
{
    public class JsonFuncKS
    {
        public static string SerializeSingle<T>(T obj)
        {
            try
            {
                return Serialize<T>(obj);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public static string SerializeCollection<T>(List<T> obj)
        {
            try
            {
                return Serialize<T>(obj);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private static string Serialize<T>(object obj)
        {
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
                MemoryStream ms = new MemoryStream();
                serializer.WriteObject(ms, obj);
                string retVal = Encoding.Default.GetString(ms.ToArray());
                ms.Close();
                ms.Dispose();
                return retVal;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        public static T DeserializeSingle<T>(string json)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
                {
                    System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
                    return (T)serializer.ReadObject(ms);
                }

            }
            catch (Exception)
            {
                return default(T);
            }

        }

        public static List<T> DeserializeCollection<T>(string json)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
                {
                    System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List<T>));
                    return (List<T>)serializer.ReadObject(ms);
                }

            }
            catch (Exception)
            {
                return default(List<T>);
            }

        }
    }
}
